package com.ysstech.schedule.utils;

import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.SpringContextUtil;
import com.ysstech.schedule.entity.ScheduleJob;
import com.ysstech.schedule.entity.ScheduleLog;
import com.ysstech.schedule.service.ScheduleLogService;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;


import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 定时任务
 */
public class ScheduleJobQuartz extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJob scheduleJobJob = (ScheduleJob) context.getMergedJobDataMap()
                .get(ScheduleJob.JOB_PARAM_KEY);
        //获取spring bean
        ScheduleLogService scheduleJobLogService = SpringContextUtil.getBean(ScheduleLogService.class);
        //数据库保存执行记录
        ScheduleLog log = new ScheduleLog();
        //任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            logger.info("任务准备执行，任务ID：" + scheduleJobJob.getId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJobJob.getBeanName(),
                    scheduleJobJob.getMethodName(), scheduleJobJob.getParams());
            Future<?> future = service.submit(task);
            future.get();
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times/1000);
            //任务状态    1：成功    2：失败
            log.setStatus(1);
            logger.info("任务执行完毕，任务ID：" + scheduleJobJob.getId() + "  总共耗时：" + times + "秒");
        } catch (Exception e) {
            logger.error("任务执行失败，任务ID：" + scheduleJobJob.getId(), e);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times/1000);
            //任务状态    1：成功    2：失败
            log.setStatus(2);
            log.setError(StringUtils.substring(e.toString(), 0, Integer.valueOf(YssEnum.YSS_BATCH_SIZE.getCode())));
        } finally {
            log.setJobId(scheduleJobJob.getId());
            log.setBeanName(scheduleJobJob.getBeanName());
            log.setMethodName(scheduleJobJob.getMethodName());
            log.setParams(scheduleJobJob.getParams());
            log.setAddTime(LocalDateTime.now());
            try {
                log.setId(DateUtil.generateUUID());
                scheduleJobLogService.save(log);
            }catch (Exception ex){
               logger.error(ex.toString());
            }

        }
    }
}
